<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--公共菜单数据-->
      <el-col :span="4" :xs="24">
        <div class="head-container">
          <el-input
            v-model="deptName"
            placeholder="请输入菜单名称"
            clearable
            size="small"
            prefix-icon="el-icon-search"
            style="margin-bottom: 20px"
          />
        </div>
        <div class="head-container">
          <el-tree
            :data="deptOptions"
            :props="defaultProps"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            ref="tree"
            node-key="id"
            default-expand-all
            highlight-current
            @node-click="handleNodeClick"
          />
        </div>
      </el-col>

      <!--用户数据-->
      <el-col :span="20">
          <!-- 左侧模块类型 -->
          <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
            <el-form-item label="模块类型" prop="geographyName">
              <el-select
                v-model="queryParams.categoryName"
                placeholder="请选择模块类型！ "
                clearable
                style="width: 240px" @change="handleGalleryChange"
              >
                <el-option
                  v-for="dict in dict.type.subsystem_gallery_icon_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>

            <!-- 右侧图标 -->
            <el-form-item>
              <div class="demo_image_preview">
                <el-col v-for="(item, index) in galleryList" :key="index" @dragstart.native="onDragStart(item)" >
                  <!-- <draggable class="drawing-board" :animation="340" group="componentsGroup"> -->
                    <el-image class="components-item"
                      style="width: 36px; height: 35px; margin-right: 1px; cursor: move;"
                      :src="baseApi + item.resourceUrl"
                      fit="cover" />
                  <!-- </draggable> -->
                </el-col>
              </div>
            </el-form-item>
          </el-form>

            <div class="card-container">
              <el-card :body-style="{width:'100%', padding: '6px 6px 6px 6px', height:'90vh'}">
                <!-- <div v-for="(image, index) in images" :key="index" class="draggable-image" >
                  <el-image
                    :src="baseApi + image.resourceUrl" 
                    :draggable="isDraggable" fit="cover"
                  />
                </div> -->
                <el-empty style="margin: 200px;" description="暂无数据" v-if="geographyUrl == ''"></el-empty>
                <div class="draggable-image-container" v-show="geographyUrl != ''">
                  <el-image class="geography_image" :src="baseApi + geographyUrl" fit="cover"/>
                  <div v-for="(item, index) in items" :key="index"
                      :style="{ left: item.dragStartX + 'px', top: item.dragStartY + 'px' }"
                      class="draggable-image">
                    <img :src="baseApi + item.resourceUrl" alt="Draggable Image" @contextmenu.prevent="onContextmenu($event,item.tiePointId)" @mousedown="startDragging($event, index)">
                  </div>
                </div>
              <!-- <el-skeleton-item v-show="geographyUrl == ''" variant="image" description="暂无数据" style="width: 100%; height: 100%;" /> -->
              <!-- <el-empty description="暂无数据" v-if="geographyUrl == ''"></el-empty> -->
              </el-card>
            </div>

          <!-- <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
              <el-button
                type="primary"
                plain
                icon="el-icon-plus"
                size="mini"
                v-hasPermi="['system:user:add']"
              >保存信息</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button
                type="danger"
                plain
                icon="el-icon-delete"
                size="mini"
                :disabled="multiple"
                v-hasPermi="['system:user:remove']"
              >删除信息</el-button>
            </el-col>
        </el-row> -->
      </el-col>
    </el-row>

    <!-- 选择设备弹窗 -->
    <el-dialog :title="title" v-if="open" :visible.sync="open" width="1200px" align-center>
      <GeographyDialog ref="child" :dragGaTiepointId="dragGaTiepointId"/>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listGallery } from '@/api/subsystem/gallery';//加载所有状态为 1正常 的图标
import { getDicts } from '@/api/system/dict/data';
import { deptTreeSelect,getGeography } from "@/api/subsystem/geography";
import { addTiePoint,updateTiePoint,findTiePointByfloorIdAndCategoryName,deleteTiePoint,getTiePointByTiePointId} from "@/api/subsystem/tiepoint";//查询绑定的点位
import { findTiePointDeviceByTiePointId,addTiePointDevice,updateTiePointDevice,deleteTiePointDeviceById} from "@/api/subsystem/tiepointDevice";//查询子系统的绑点关联关系
import GeographyDialog from './geography-dialog.vue';//绑定设置弹窗
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import draggable from 'vuedraggable'

export default {
  name: "User",
  dicts: ['subsystem_gallery_icon_type', 'sys_floor_type'],
  components: { 
    Treeselect,
    draggable,
    GeographyDialog
   },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 根路径
      baseApi: process.env.VUE_APP_BASE_API,
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      galleryList: [],  // 图库管理表格数据
      geographyUrl: "", // 楼层CAD背景图
      
      // 部门树选项
      deptOptions: undefined,
      // 部门名称
      deptName: undefined,
      // 日期范围
      dateRange: [],
      // 岗位选项
      postOptions: [],
      // 角色选项
      roleOptions: [],
      defaultProps: {
        children: "children",
        label: "label"
      },
      //模块类型查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        categoryName: '',
        galleryName: '',
        resourceUrl: null,
        status: null,
        isAsc: 'desc',
      },
      queryGeographyParams: {
        floorId: undefined,
        galleryId: undefined,
        dragStartX: 0,
        dragStartY: 0
      },
      items: [],
      draggingIndex: null,
      dragStartAxleX: 0,
      dragStartAxleY: 0,
      dragGaTiepointId: undefined,
      contextMenuData: [
        {
          label: "更新位置",
          // 以element-ui图标为例实现右键菜单，图标会为被渲染为<i class="icon"></i>
          icon: "icon el-icon-location",
          onClick: () => {
            this.renewCoordinate();
          },
        },
        {
          label: "绑定设备",
          icon: "icon el-icon-share",
          divided: true,
          onClick: () => {
            this.bindDevice();
          },
        },
        {
          label: "删除设备",
          icon: "icon el-icon-delete",
          divided: true,
          onClick: () => {
            this.bindDelete();
          },
        }
      ],
    };
  },
  watch: {
    // 根据名称筛选部门树
    deptName(val) {
      this.$refs.tree.filter(val);
    }
  },
  created() {
    this.getDeptTree();//页面初始化查询左侧公共菜单
    // 获取数据
    this.getDatas();
    // this.getGeographyUrl();
    this.dragging();
  },
  methods: {
    //保存数据
    submitForm(){
      const selectGeographyDialogTable = this.$refs.child.rightTableData;//获取弹窗右侧table选中的值
      //判断当前子系统图标在库中是否已经存在绑点的关联关系
      findTiePointDeviceByTiePointId(this.dragGaTiepointId).then((response) => {
        if (response.code === 200) {
          if(response.data == undefined){//说明没有关联关系
            if(selectGeographyDialogTable.length > 0){
              //this.dragGaTiepointId
              //selectGeographyDialogTable[0].deviceName+"================="+selectGeographyDialogTable[0].serialNumber
              addTiePointDevice(this.dragGaTiepointId,selectGeographyDialogTable[0].deviceId).then((response) => {
                this.$modal.msgSuccess("绑定成功！");
              })
            }
          }else{
            if(selectGeographyDialogTable.length > 0){//更新
              //this.dragGaTiepointId     selectGeographyDialogTable[0].deviceId
              //selectGeographyDialogTable[0].deviceName+"================="+selectGeographyDialogTable[0].serialNumber
              updateTiePointDevice(this.dragGaTiepointId,selectGeographyDialogTable[0].deviceId).then((response) => {
                this.$modal.msgSuccess("更新绑定成功！");
              })
            }else{
              //删除
              deleteTiePointDeviceById(this.dragGaTiepointId).then((response) => {
                this.$modal.msgSuccess("解绑成功！");
              })
            }
          }
        }
      });

      // 
      // if(selectGeographyDialogTable.length > 0){
      //   //判断穿梭框右侧是否已经选中设备，如果有设备则存库
      //   alert(this.dragGaTiepointId);
      //   //alert();
      // }else{
      //   //穿梭框右侧没有数据的话，先查库看是否存在绑定关系，如果存在则删除
      // }

      // selectGeographyDialogTable.forEach((item, index) => {
      //   alert(item.deviceName);
      // });
      this.open = false;
      this.$refs.child.rightTableData = [];
    },
    //关闭弹窗
    cancel(){
      this.open = false;
    },
    //更新位置
    renewCoordinate(){
      //判断当前子系统图标是否已经存在点位
      if(this.dragGaTiepointId == undefined){
        addTiePoint(this.queryGeographyParams).then(response => {
          this.$modal.msgSuccess("新增成功");
        });
      }else{
        if(this.queryGeographyParams.dragStartX != 0 && this.queryGeographyParams.dragStartY != 0){
          updateTiePoint(this.dragGaTiepointId,this.queryGeographyParams.dragStartX,this.queryGeographyParams.dragStartY).then(response => {
            if (response.code === 200) {
              this.queryGeographyParams.dragStartX = 0;
              this.queryGeographyParams.dragStartY = 0;
              this.$modal.msgSuccess("修改成功");
            }
          });
        }
      }
      this.getGeographyUrl();
    },
    //绑定设备
    bindDevice(){
      if(this.dragGaTiepointId == undefined){
        this.$modal.msgWarning("请确定图标位置并更新！");
      }else{
        this.title = "绑定【" + this.queryParams.categoryName + "】子系统设备";
        this.open = true;
      }
    },
    //删除图标
    bindDelete(){
      if(this.dragGaTiepointId == undefined){
        this.getGeographyUrl();
      }else{
        deleteTiePoint(this.dragGaTiepointId).then(response => {
          this.$modal.msgSuccess("删除成功");
          this.getGeographyUrl();
          //this.open = false;
          //this.getList();
        });
        //删除绑定的设备及表关系
      }
    },
    //右键菜单事件
    onContextmenu(event,tiePointId) {
      this.dragGaTiepointId = tiePointId;
      this.$contextmenu({
        items: this.contextMenuData,
        event, // 鼠标事件信息
        customClass: 'custom-class', // 自定义菜单 class
        zIndex: 999, // 菜单样式 z-index
        minWidth: 160 // 主菜单最小宽度
      });
      return false;
    },
    //拖拽启动
    onDragStart(item,event){
      this.queryGeographyParams.galleryId = item.galleryId;
      const newItem = {
        resourceUrl: item.resourceUrl,
        dragStartX: 0, // 图像宽度减去一些边距
        dragStartY: 0 // 图像高度减去一些边距
      };
      this.items.push(newItem);
    },
    //拖动方法
    startDragging(event, index) {
      this.draggingIndex = index;
      this.dragStartAxleX = event.clientX;
      this.dragStartAxleY = event.clientY;
      document.addEventListener('mousemove', this.dragging);
      document.addEventListener('mouseup', this.stopDragging);
    },
    dragging(event) {
      if (this.draggingIndex !== null) {
        const deltaX = event.clientX - this.dragStartAxleX;
        const deltaY = event.clientY - this.dragStartAxleY;
        this.items[this.draggingIndex].dragStartX += deltaX;
        this.items[this.draggingIndex].dragStartY += deltaY;
        this.dragStartAxleX = event.clientX;
        this.dragStartAxleY = event.clientY;
        //输出新坐标
        this.queryGeographyParams.dragStartX = this.items[this.draggingIndex].dragStartX;
        this.queryGeographyParams.dragStartY = this.items[this.draggingIndex].dragStartY;
        //console.log('图标编号是====='+this.draggingIndex+`新坐标================`+this.items[this.draggingIndex].dragStartX +"============"+this.items[this.draggingIndex].dragStartY);
      }
    },
    stopDragging() {
      this.draggingIndex = null;
      document.removeEventListener('mousemove', this.dragging);
      document.removeEventListener('mouseup', this.stopDragging);
    },
    //-----------------------------------------------------------------------------------------------------------------------------------------------------------
    //获取子系统图标
    async getDatas() {
      const dictType = 'subsystem_gallery_icon_type';
      const { data } = (await this.getCategoryTypes(dictType)) || [];
      this.queryParams.categoryName = data[0].dictValue;
      this.queryParams.status = "1";
      this.getGalleryList();
    },
    // 获取种类
    getCategoryTypes(dictType) {
        return new Promise((resolve, reject) => {
          getDicts(dictType)
            .then((res) => {
                resolve(res);
            })
            .catch((error) => {
                reject(error);
            });
        });
      },
      getGalleryList() {
        this.loading = true;
        listGallery(this.queryParams).then((response) => {
          if (response.code === 200) {
              this.galleryList = response.rows;
              this.total = response.total;
          }
          this.loading = false;
        });
      },
      //模块类型选择
      handleGalleryChange(value) {
        this.queryParams.pageNum = 1;
        this.queryParams.categoryName = value;
        this.queryParams.status = "1";
        this.single = true;
        this.multiple = true;
        this.getGalleryList();
        this.queryCoordinate();
      },


      //-----------------------------------------------------------------------------------------------------------------------------------------------------------
    /** 查询部门下拉树结构 */
    getDeptTree() {
      deptTreeSelect().then(response => {
        this.deptOptions = response.data;
        this.queryGeographyParams.floorId = this.deptOptions[0].id;//获取左侧tree的根节点传给右侧查询楼层cad背景图
        this.getGeographyUrl();
      });
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryGeographyParams.floorId = data.id;
      this.getGeographyUrl();
    },

    /** 查询楼层CAD背景图 */
    getGeographyUrl() {
      this.loading = true;
      getGeography(this.queryGeographyParams.floorId).then(response => {
        //判断查询菜单是否设置了背景图
        if (response.data == undefined) {
          this.geographyUrl = ""
        }else{
          this.geographyUrl = response.data.geographyUrl;
          this.queryCoordinate();
        }
      });
    },
    queryCoordinate(){
      //alert("根据该节点编号查询关于他的所有子系统图标===="+floorId);
      findTiePointByfloorIdAndCategoryName(this.queryGeographyParams.floorId,this.queryParams.categoryName).then(response => {
        this.items = response.data;
      });
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
  }
};
</script>

<style>
  .demo_image_preview{
    display: flex;          /* 使div变为Flex容器 */
    flex-wrap: nowrap;      /* 避免图片换行 */
  }

  .card-container{
    margin-bottom: 20px;
    width: 100%;
    height: 100%;
    position: relative;
  }

  .drawing-board {
    height: 100%;
    position: relative;
  }

  .draggable-image-container{
    position: relative;
  }

  .geography_image{/** 楼层背景样式 */
    width: 100%; 
    height: 88.6vh; 
    z-index: 1;
    display: block;
  }

  .draggable-image {
    position: absolute;
    cursor: move;
    z-index: 999;
  }

  .draggable-image img{
    width: 40px;
    height: 45px;
  }
</style>
